﻿using Azure;
using Azure.Core;
using DataModels.Dto;
using DataModels.Dto.House;
using DataModels.Entities.AuthCore;
using DataModels.Entities.Base;
using DataModels.Entities.House;
using DataModels.Entities.ParkingLot;
using Dm.util;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SEGIService.Service.Basic.House;
using SqlSugar;
using System.Threading.Tasks;
using Utils;

namespace Services.House
{
    public class HouseService(SqlSugarClient db, SEGIHouseService sEGIHouseService) : BaseService(db)
    {
        protected readonly SEGIHouseService _sEGIHouseService = sEGIHouseService;


        public ResponseModel GetHouseInfoBySIGE(Guid? projectid = null)
        {
            List<int?> sigeid = GetCustIdListBySIGE();
            var data1 = db.Queryable<CustomerHouseRelation, Customer, HousingBasic, Projects, Building, Unit>((chr, c, h, p, bu, unit) => new object[]
            {
                JoinType.Left, chr.CustId == c.CustId,
                JoinType.Left, chr.HouseId == h.HouseId,
                JoinType.Left,chr.OrganId == p.CommunityId,
                JoinType.Left,h.BuildId==bu.BuildId,
                JoinType.Left,h.UnitId==unit.unitId
            })
                .Where(chr =>  sigeid.Contains(chr.CustId))
                .Where(chr => chr.CustStatus == "1000" || chr.CustStatus == "1001")
                .Where(chr => chr.RelType == "1") //1房屋3车位
                .WhereIF(projectid != null, chr => chr.OrganId == GetOrganIdBySIGE((Guid)projectid))
                .Select("chr.*, h.UUID as HouseUUId, c.UUID as CustomerUUId,p.ProjectName as ProjectName ,p.UUID as ProjectUUID, bu.UUID as BuildUUID, unit.UUID as unitUUID")
                .ToList();
            return Success(data1);
        }

        public ResponseModel GetHouseInfoBySIGE_test(Guid? projectid = null)
        {
            int sigeid = GetCustIdBySIGE();
            var data = db.Queryable<house_customer_test>()
                .Where(chr => chr.sccustId == sigeid)
                .ToList();
            return Success(data);
        }




        // 获取房屋信息
        public ResponseModel GetHouseInfo(Guid? projectid = null)
        {
            var res = db.Queryable<Projects, Properties, HousingBasic, HousingUserRelation>((p, pp, hb, hur) => new object[]
            {
                JoinType.Left, p.UUID == pp.ProjectUUID,
                JoinType.Left, pp.UUID == Guid.Parse(hb.PropertiesUUID),
                JoinType.Left, hb.UUID == hur.HouseUUID
            })
                .WhereIF(projectid.HasValue, p => p.UUID == projectid)
                .Where((p, pp, hb, hur) => hur.UserUUID == new Guid("a75549c4-6a10-4bc8-8265-8fb08fe2a340"))
                .Where((p, pp, hb, hur) => hur.UserUUID == UserUUID)
                // 关系正常存续
                .Where((p, pp, hb, hur) => hur.Status == DataModels.Enums.House.HousingUserRelationStatus.Active)
                .Where((p, pp, hb, hur) => !hur.EndDate.HasValue || hur.EndDate >= DateTime.Now)
                .Select((p, pp, hb, hur) =>
                new HouseInfoDto
                {
                    HouseId = hb.UUID,
                    ProjectId = p.UUID,
                    ProjectName = p.ProjectName,
                    BuildingNo = pp.BuildingNo,
                    UnitNo = pp.UnitNo,
                    FloorNo = pp.FloorNo,
                    RoomNo = pp.RoomNo,
                    RelationType = hur.RelationType,
                    UsageType = hb.UsageType,
                    Remark = hur.Remark
                })
                .ToList()
                ;
            // 转换为最终响应对象
            var response = res.Select(dto => new HouseInfoResponse
            {
                HouseId = dto.HouseId,
                ProjectId = dto.ProjectId,
                ProjectName = dto.ProjectName,
                BuildingNo = dto.BuildingNo,
                UnitNo = dto.UnitNo,
                FloorNo = dto.FloorNo,
                RoomNo = dto.RoomNo,
                RelationType = dto.RelationType.GetDescription(),
                UsageType = dto.UsageType.GetDescription(),
                Remark = dto.Remark
            }).ToList();

            return Success(response);
        }

        // 获取房产所有用户信息
        public ResponseModel GetHouseUser(Guid HouseUUID)
        {
            string GetCustTypeName(string custType)
            {
                return custType switch
                {
                    "1000" => "业主",
                    "1001" => "业主成员",
                    "2000" => "租户",
                    "2001" => "租户成员",
                    "4000" => "访客",
                    _ => "未知类型"
                };
            }
            //查询这个房子的全部客户
            int HouseId = GetHouseIdBySIGE(HouseUUID);
            var res = db.Queryable<CustomerHouseRelation>().Where(x => x.HouseId == HouseId && (x.CustStatus == "1000" || x.CustStatus == "1001")).ToList();
            var obj = new List<GetHouseUserResponse>();
            foreach (var item in res)
            {
                //临时解决一下
                var cust = db.Queryable<Customer>().Where(c => c.CustId == item.CustId).First();
                if (cust != null)
                {
                    var data = new GetHouseUserResponse
                    {
                        UserID = cust.UUID,
                        UserName = cust.Name,
                        AvatarUrl = cust.PicUrl,
                        Phone = cust.Tel1,
                        EndDate = item.OutDate,
                        CustType = item.CustType,
                        CustTypeName = GetCustTypeName(item.CustType)
                    };
                    obj.Add(data);
                }


            }
            return Success(obj);
        }


        // 更新房屋信息
        public async Task<ResponseModel> EditHouseInfo(EditHouseInfo info)
        {
            int sigeHouseid= GetHouseIdBySIGE(info.HouseUUID);
            CustomerHouseRelation model =db.Queryable<CustomerHouseRelation>()
                .Where(p => p.CustStatus == "1000" || p.CustStatus == "1001")
                .Where(p => p.HouseId == sigeHouseid)
                .Where(p => p.Name == info.OwnerTenantName)
                .Where(p => (p.Tel1 == info.OwnerTenantPhone || p.Tel2 == info.OwnerTenantPhone))
                .First();

            if (model == null)
            {
                return Error("未找到对应的房屋信息");
            }
            if (string.IsNullOrWhiteSpace(info.ApplicantName))
                return Error("请填写申请人姓名");
            if (!info.ProjectUUID.Equals(info.ProjectUUID))
                return Error("请选择项目");

            Customer modelU1 = db.Queryable<Customer>().Where(u => u.UUID == UserUUID && u.CustStatus == "1").First();
            if (modelU1 == null)
            {
                return Error("登录用户不存在");
            }
            // 更新用户信息
            modelU1.Name = info.ApplicantName;
            //modelU1.OrganId = Convert.ToInt32(GetOrganIdBySIGE(info.ProjectUUID));
            db.Updateable(modelU1).ExecuteCommand();

            //调用后台  房屋/车位绑定审核通过接口
            string url = $"http://127.0.0.1:7002/api/House/PushsigeCustomer?outApplicantUUID={UserUUID}&sigeHouseid={sigeHouseid}";
            var dataJsono = new
            {
                outApplicantUUID = UserUUID,
                sigeHouseid = sigeHouseid
            };
            using (var client = new HttpClient())
            {
                StringContent requestContent = new StringContent(JsonConvert.SerializeObject(dataJsono), System.Text.Encoding.UTF8, "application/json");
                var response =await client.PostAsync(url, requestContent);
                string responseContent = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    Console.WriteLine($"发送失败：{response.StatusCode}，响应：{responseContent}");
                }
                else
                {
                    Console.WriteLine($"发送成功，响应：{responseContent}");
                    return Success("房屋/车位绑定审核通过");
                }
                return null;
            }
        }

        /// <summary>
        /// 申请认证
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public ResponseModel HouseCertification(HouseCertificationInfo info)
        {
            try
            {
                int objId = 0;
                if (info.RelType == 1)
                {
                    HousingBasic hsmodel = db.Queryable<HousingBasic>().Where(hb => hb.UUID == Guid.Parse(info.HouseUUID)).First();
                    if (hsmodel == null)
                    {
                        return Error("房屋不存在");
                    }
                    objId = hsmodel.HouseId; // 获取四格ID
                }
                else if (info.RelType == 3)
                {
                    var parkingSpace = db.Queryable<ParkingSpace>().Where(p => p.UUID == Guid.Parse(info.ParkingUUID)).First();
                    if (parkingSpace == null)
                    {
                        return Error("车位信息不存在");
                    }
                    objId = parkingSpace.ParkingId; // 获取四格ID
                }

                HouseCertification hcmodel = db.Queryable<HouseCertification>()
                    .Where(hc => hc.RelType == info.RelType && hc.ObjId == objId)
                    .Where(hc => hc.Status == DataModels.Enums.GeneralEnum.ApprovalStatus.PendingApproval)
                    .First();

                if (hcmodel != null)
                {
                    return Error("认证已在审批中");
                }
                if (string.IsNullOrWhiteSpace(info.ApplicantName))
                    return Error("请填写申请人姓名");
                if (!info.ProjectUUID.Equals(info.ProjectUUID))
                    return Error("请选择项目");

                HouseCertification model = new()
                {
                    RelType = info.RelType,
                    RelationType = info.RelationType,
                    HouseUUID = info.RelType == 1 ? info.HouseUUID : string.Empty,
                    ParkingUUID = info.ParkingUUID,
                    Status = DataModels.Enums.GeneralEnum.ApprovalStatus.PendingApproval,
                    ObjId = objId,
                    ApplicantUUID = UserUUID,
                    ApplicantTempName = info.ApplicantName,
                    ApplicantCustId = GetCustIdBySIGE(),
                    UpdateTime = DateTime.Now
                };

                Customer modelU1 = db.Queryable<Customer>().Where(u => u.UUID == UserUUID && u.CustStatus == "1").First();
                if (modelU1 == null)
                {
                    return Error("登录用户不存在");
                }
                // 更新用户信息
                db.BeginTran();
                //modelU1.Name = info.ApplicantName;
                //modelU1.OrganId = Convert.ToInt32(GetOrganIdBySIGE(info.ProjectUUID));
                //db.Updateable(modelU1).ExecuteCommand();
                HouseCertification wo = db.Insertable(model).ExecuteReturnEntity();
                info.Urls.Select(url => new Attachment
                {
                    BusinessId = wo.UUID,
                    Url = url,
                    CreatedBy = UserUUID
                }).ToList().ForEach(a =>
                {
                    db.Insertable(a).ExecuteCommand();
                });
                db.CommitTran();
                return Success();
            }
            catch
            {
                db.RollbackTran();
                //return Error(ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 业主邀请成员
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<ResponseModel> OwnerInvitesMembers(HouseCertificationOwnerInvitesMembersInfo info)
        {
            try
            {
                int objId = 0;
                HousingBasic hsmodel = db.Queryable<HousingBasic>().Where(hb => hb.UUID == Guid.Parse(info.HouseUUID)).First();
                if (info.RelType == 1)
                {
                    if (hsmodel == null)
                    {
                        return Error("房屋不存在");
                    }
                    objId = hsmodel.HouseId; // 获取四格ID
                }
                else if (info.RelType == 3)
                {
                    var parkingSpace = db.Queryable<ParkingSpace>().Where(p => p.UUID == Guid.Parse(info.ParkingUUID)).First();
                    if (parkingSpace == null)
                    {
                        return Error("车位信息不存在");
                    }
                    objId = parkingSpace.ParkingId; // 获取四格ID
                }

                if (string.IsNullOrWhiteSpace(info.ApplicantName))
                    return Error("请填写被邀请人姓名");
                if (string.IsNullOrWhiteSpace(info.ApplicantPhone))
                    return Error("请填写被邀请人手机号");
                if (!info.ProjectUUID.Equals(info.ProjectUUID))
                    return Error("请选择项目");

                Customer modelU1 = db.Queryable<Customer>().First(u => (u.Tel1 == info.ApplicantPhone || u.Tel2 == info.ApplicantPhone) && u.OrganId== hsmodel.OrganId);
                if (modelU1 == null)
                {
                    // 1. 创建新用户
                    Guid uuid = Guid.NewGuid();
                    var newUser = new Customer
                    {
                        UUID = uuid,
                        Tel1 = info.ApplicantPhone,
                        Name = info.ApplicantName,
                        ThirdCustId = uuid.ToString(),   //
                        EstablishDate = DateTime.Now,
                        ChangeTime = DateTime.Now,
                        CustStatus = "1",
                        dataSources = "微信邀请注册"  //
                    };
                    db.Insertable(newUser).ExecuteCommand();
                    //调用后台  房屋/车位绑定审核通过接口
                    string url = $"http://127.0.0.1:7002/api/House/PushsigeCustomer?outApplicantUUID={uuid}&sigeHouseid={objId}&RelType=1&RelationType={(int)info.RelationType}";
                    var dataJsono = new
                    {
                        outApplicantUUID = uuid,
                        sigeHouseid = objId
                    };
                    using (var client = new HttpClient())
                    {
                        StringContent requestContent = new StringContent(JsonConvert.SerializeObject(dataJsono), System.Text.Encoding.UTF8, "application/json");
                        var response = await client.PostAsync(url, requestContent);
                        string responseContent = await response.Content.ReadAsStringAsync();

                        if (!response.IsSuccessStatusCode)
                        {
                            Console.WriteLine($"发送失败：{response.StatusCode}，响应：{responseContent}");
                        }
                        else
                        {
                            Console.WriteLine($"发送成功，响应：{responseContent}");
                            return Success("房屋/车位邀请绑定通过");
                        }
                        return null;
                    }
                }

                return Error("该用户已在该小区有房");
            }
            catch
            {
                db.RollbackTran();
                //return Error(ex.Message);
                throw;
            }
        }
    }
}
